package com.service.user.impl;

import com.service.user.AuthCodeService;
import com.zhenzi.sms.ZhenziSmsClient;

import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/** 验证码服务类，提供发送验证码的功能 */
@Service
public class AuthCodeServiceImpl implements AuthCodeService {

  /**
   * 发送并返回验证码
   *
   * @param phoneNumber 需发送验证码的手机号
   * @return 发送成功返回验证码，失败返回0
   */
  @Override
  public int sendAuthCodeToVerify(String phoneNumber) {
    int authCode = (int) (Math.random() * 100000);
    if (authCode < 10000) {
      authCode += 10000;
    }
    Map<String, Object> params = new HashMap<>(3);
    params.put("number", phoneNumber);
    params.put("templateId", "6931");
    String[] templateParams = new String[2];
    templateParams[0] = String.valueOf(authCode); // 验证码
    templateParams[1] = "5"; // XXX内有效
    params.put("templateParams", templateParams);
    String result;
    ZhenziSmsClient client =
        new ZhenziSmsClient(
            "https://sms_developer.zhenzikj.com", "110109", "474f72f5-bdbc-4c62-a5bf-6dd62d4615be");
    try {
      result = client.send(params);
      System.out.println(result);
    } catch (Exception e) {
      e.printStackTrace();
      return -1;
    }
    if (result.contains("发送成功")) {
      return authCode;
    } else {
      return -1; // 发送失败
    }
  }
}
